package com.zztl.infiniteBand.ui.activity

import android.app.Activity
import android.content.Intent
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import butterknife.OnClick
import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseMvpActivity
import com.zztl.infiniteBand.model.CheckAddressBean
import com.zztl.infiniteBand.model.PlatformBean
import com.zztl.infiniteBand.model.TransferBean
import com.zztl.infiniteBand.net.requestBean.GetVerifyRequest
import com.zztl.infiniteBand.net.requestBean.PayoutRequest
import com.zztl.infiniteBand.presenter.PayoutPresenter
import com.zztl.infiniteBand.storage.BillPreference
import com.zztl.infiniteBand.storage.Constans
import com.zztl.infiniteBand.storage.PreferenceKeys
import com.zztl.infiniteBand.ui.view.dialog.DismissListener
import com.zztl.infiniteBand.ui.view.dialog.MentionDialog
import com.zztl.infiniteBand.ui.view.mvpview.PayoutView
import com.zztl.infiniteBand.util.DataFormatUtil
import com.zztl.infiniteBand.util.PermissionUtils
import com.zztl.infiniteBand.util.toast
import kotlinx.android.synthetic.main.activity_mention.*

class MentionActivity : BaseMvpActivity<PayoutView, PayoutPresenter>(), PayoutView {


    lateinit var mPayoutPresenter: PayoutPresenter
    private val SCAN_CODE = 10
    private val ADDRESS = 20

    private var mServiceCharge: Double = 0.toDouble()
    private var mUseableAssets: String? = null
    private var mMentionDialog: MentionDialog? = null
    private var mActual: String? = null   //实际到账数量
    private var mCharge: String? = null   //手续费
    private var isExternalPlatform: Boolean = false  //是否是外平台
    private var hasResult: Boolean = false   //是否扫描地址结果的回调


    private val mPermissionGrant = object : PermissionUtils.PermissionGrant {
        override fun onPermissionGranted(requestCode: Int) {
            when (requestCode) {
                PermissionUtils.CODE_CAMERA -> try {
                    val intent = Intent(this@MentionActivity, ScanActivity::class.java)
                    showActivityForResult(intent, SCAN_CODE)
                } catch (e: Exception) {
                }
            }
        }
    }


    override fun setLayoutId(): Int = R.layout.activity_mention


    override fun initBase() {
        setTitle(getString(R.string.提币))
        intent.getStringExtra(Constans.USEABLEASSETS)?.apply {
            tv_useable_assets.text = "$this"
        }?.let {
            mUseableAssets = DataFormatUtil.converTxtPoint2(it).apply {
                et_number.hint = getString(R.string.剩余可提币数量)+this
            }
        }

      /*  mUseableAssets = DataFormatUtil.converTxtPoint2()?.apply {

            tv_useable_assets.text = "$this"
        }*/

        mPayoutPresenter.getPlatformInfo("common", this)
        initListener()
    }


    override fun createPresenter(): PayoutPresenter {
        mPayoutPresenter = PayoutPresenter()
        return mPayoutPresenter
    }


    private fun initListener() {
        et_number.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
            if (!hasFocus) {
                et_number.text.toString().trim()
                        .let {
                            if (it.isNotEmpty()) {
                                if (it.toDouble() < 0.01) {
                                    et_number.setText(0.01.toString())
                                }
                            }
                        }


            }
        }
        et_number.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable) {
                val text = s.toString()
                val posDot = text.indexOf(".")
                if (posDot <= 0) {
                    //temp
                    try {
                        if (text.toDouble() > mUseableAssets!!.toDouble()) {
                            //                            hintUseable = mUseableAssets;
                            et_number.setText(mUseableAssets)
                            setActualMoney(mUseableAssets?.toDouble(), isExternalPlatform)
                            return
                        }
                    } catch (e: Exception) {
                        setActualMoney(0.0, isExternalPlatform)
                    }

                } else if (text.length - posDot - 1 > 2) {
                    s.delete(posDot + 2, text.length - 1)
                }
                try {
                    if (text.toDouble() > mUseableAssets!!.toDouble()) {
                        et_number.setText(mUseableAssets)
                    }
                    et_number.text.toString().trim()
                            .apply {
                                if (this.isNotEmpty() && this.toDouble() > 0) {
                                    setActualMoney(this.toDouble(), isExternalPlatform)
                                }
                            }
                } catch (e: Exception) {
                    setActualMoney(0.0, isExternalPlatform)
                }

                btn_sure.isEnabled = isClickable()

            }
        })

        et_addr.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
            et_addr.text.toString().trim { it <= ' ' }.let { address ->
                if (!hasFocus && et_addr.length() > 25) {
                    isExternalPlatform = false
                    if (address.length >= 34) {
                        mPayoutPresenter.checkAddress(address, this@MentionActivity)
                    }
                }
            }

        }

        et_addr.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                s.toString().let {
                    if (it.length < 34) {
                        isExternalPlatform = false
                        et_number.text.toString().trim().let {
                            if (it.isNotEmpty()) {
                                setActualMoney(it.toDouble(), isExternalPlatform)
                            }
                        }

                    } else {
                        mPayoutPresenter.checkAddress(it, this@MentionActivity)
                    }
                }


            }

            override fun afterTextChanged(s: Editable) {
                btn_sure.isEnabled = isClickable()
            }

        })
    }


    @OnClick(R.id.btn_scan, R.id.btn_record, R.id.btn_sure, R.id.btn_all)
    fun click(view: View) {
        when (view.id) {
            R.id.btn_scan -> PermissionUtils.requestPermission(this, PermissionUtils.CODE_CAMERA, mPermissionGrant)
            R.id.btn_record -> showActivityForResult(this, AddressRecordActivity::class.java, ADDRESS)
            R.id.btn_sure -> {
                if (et_addr.text.isEmpty()) {
                    this toast getString(R.string.提币地址不能为空)
                    return
                }
                try {
                    if (et_number.text.isEmpty() || java.lang.Double.valueOf(et_number.text.toString().trim { it <= ' ' }) <= 0) {
                        this toast getString(R.string.转出金额必须大于0)
                        return
                    }
                } catch (e: Exception) {
                    this toast getString(R.string.请输入正确的转账金额)
                    return
                }

                showDialog()
            }
            R.id.btn_all ->

                et_number.setText(mUseableAssets!! + "")
            else -> {
            }
        }
    }


    private fun isClickable(): Boolean {
        try {
            return et_addr.text.isNotEmpty() && et_number.text.isNotEmpty() && java.lang.Double.valueOf(et_number.text.toString().trim { it <= ' ' }) > 0
        } catch (e: Exception) {

        }
        return false
    }

    private fun showDialog() {

        mMentionDialog = MentionDialog.Builder(this)
                .setMessage(getString(R.string.提示))
                .setMoney(et_number.text.toString().trim { it <= ' ' }+" IFR")
                .setCharge("$mCharge IFR")
                .setReceiverNum("$mActual IFR")
                .setClickListener(object : MentionDialog.Builder.ClickListener {
                    override fun cancel() {

                    }

                    override fun comfirm(pwd: String, code: String) {
                        if (mPayoutPresenter.check(et_addr.text.toString().trim { it <= ' ' }, et_number.text.toString().trim { it <= ' ' }, code, pwd)) {
                            mPayoutPresenter.payout(PayoutRequest(et_addr.text.toString().trim { it <= ' ' }, et_number.text.toString().trim { it <= ' ' },
                                    code, pwd), this@MentionActivity)
                        }
                    }

                    override fun getCode() {
                        val phone = BillPreference.getApp(PreferenceKeys.DEFAULT_PHONE.name, "") as String
                        val countryCode = BillPreference.getApp(PreferenceKeys.COUNTYRCODE.name, "86") as String
                        mPayoutPresenter.getCode(GetVerifyRequest(phone, "3", "+" + countryCode), this@MentionActivity)
                        mPayoutPresenter.startCountDown(this@MentionActivity)
                    }
                }).setDismissListener(object : DismissListener {
                    override fun dismiss() {
                        mPayoutPresenter.destoryTimer()
                    }
                }).create().apply {
                    showDialog()
                }
    }
//    { ) }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant)

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            var address = ""
            if (requestCode == SCAN_CODE) {
                hasResult = true
                address = data.getStringExtra(Constans.SCAN_RESULT)
            } else if (requestCode == ADDRESS) {
                address = data.getStringExtra("address")
            }
            address.filter {
                it.toString().isNotEmpty()
            }.let {
                et_addr.setText(it)
                if (!et_addr.hasFocus() && it.length >= 34) {
                    mPayoutPresenter.checkAddress(address, this)
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }


    override fun getPaltformSuccess(bean: PlatformBean) {
        bean.data?.let {
            mServiceCharge = it.rate
            val content = String.format(getString(R.string.转账须知),
                    it.minTransfer.toString() + "",
                    it.maxTransfer.toString() + "",
                    mServiceCharge.toString() + "")
            mention_hint.text = content
        }

        //        et_number.setHint(getString(R.string.最小提币数量) + bean.getData().getBill().getMinTransfer());
    }

    override fun payoutSuccess(bean: TransferBean) {
        mMentionDialog?.run {
            if(isShowing) dismiss()
        }
        val intent = Intent(this, MentionSuccessActivity::class.java)
        intent.putExtra("address", bean.data!!.targetAddress)
        intent.putExtra("charge", bean.data!!.serviceCharge)
        intent.putExtra("txid", bean.data!!.txid)
        intent.putExtra("state", bean.data!!.state)
        intent.putExtra("money", et_number.text.toString().trim { it <= ' ' })
        skipActivity(intent)
    }

    override fun checkSuccess(bean: CheckAddressBean) {
        et_number.isEnabled = true
        isExternalPlatform = !bean.data!!.result.equals("true")

        if (hasResult) {
            et_number.text.toString().let {
                if (it.isNotEmpty()) {
                    setActualMoney(it.toDouble(), isExternalPlatform)
                }
            }
        }
    }

    /**
     * 设置实际到账的金额
     *
     * @param money              转出金额
     * @param isExternalPlatform 是否是外平台
     */
    private fun setActualMoney(money: Double?, isExternalPlatform: Boolean) {
        if (isExternalPlatform) {
            mCharge = DataFormatUtil.converTxtPoint4(mServiceCharge / 100 * money!!)
            mActual = DataFormatUtil.converTxtPoint4((100 - mServiceCharge) / 100 * money)
            tv_reveicer_number.text = " ${mActual}IFR"
        } else {
            mCharge = "0.00"
            mActual = DataFormatUtil.converTxtPoint4(money!!)
            tv_reveicer_number.text = "${DataFormatUtil.converTxtPoint4(money)} IFR"
        }

    }

    override fun getCodeFail(message: String) {
        this toast message
        mPayoutPresenter.resetSmsView()
    }

    override fun getCodeFail() {

    }

    override fun getCodeSuccess() {

    }

    override fun setDisableView(count: Int) {
        mMentionDialog!!.setBtnUsable(false)
        mMentionDialog!!.setBtnTxt("(" + count + ")" + getString(R.string.重新发送))
        mMentionDialog!!.setBtnColor(resources.getColor(R.color.color_ACA593))
    }

    override fun setUseableView() {
        mMentionDialog!!.setBtnUsable(true)
        mMentionDialog!!.setBtnTxt(getString(R.string.发送验证码))
        mMentionDialog!!.setBtnColor(resources.getColor(R.color.color_007aff))
    }


}
